package cn.git.bbs.core.controller;

import cn.git.bbs.core.service.upload.UploadPicService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
public class UploadPicController {

    @Autowired
    private UploadPicService uploadPicService;

    @Value("${URL}")
    private String URL;
    @RequestMapping("/upload/uploadPic")
    public void uploadPic(@RequestParam(required = false)MultipartFile pic, HttpServletResponse response) throws IOException {

        String path =  uploadPicService.uploadPic(pic.getBytes(),pic.getOriginalFilename(),pic.getSize());
        String url = URL+path;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url",url);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(jsonObject.toString());
    }

    @RequestMapping("/upload/uploadPics")

    public @ResponseBody List<String> uploadPics(@RequestParam(required = false)MultipartFile[] pics) throws IOException {

        List<String> urls = new ArrayList<String>();
        for (MultipartFile pic : pics) {
            String path = uploadPicService.uploadPic(pic.getBytes(), pic.getOriginalFilename(), pic.getSize());
            String url = URL+path;
            urls.add(url);
        }
        return urls;
    }
//    /upload/uploadFck.do'
    @RequestMapping("/upload/uploadFck.do")
    public void uploadFck(HttpServletRequest request,HttpServletResponse response) throws IOException {

        MultipartRequest mr = (MultipartRequest)request;

        Map<String, MultipartFile> fileMap = mr.getFileMap();
        Set<Map.Entry<String, MultipartFile>> entries = fileMap.entrySet();
        for (Map.Entry<String, MultipartFile> entry: entries) {
            MultipartFile value = entry.getValue();
            String path = uploadPicService.uploadPic(value.getBytes(),value.getOriginalFilename(),value.getSize());
            String url = URL+path;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url",url);
            jsonObject.put("error",0);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(jsonObject.toString());
        }

    }

}
